from gnuradio import gr, uhd, blocks
import numpy as np
import time


class USRPDiagnostic(gr.top_block):
    def __init__(self):
        gr.top_block.__init__(self)

        # 初始化USRP
        self.usrp = uhd.usrp_source(
            ",".join(("=serial=31A92E2", "")),
            uhd.stream_args(
                cpu_format="fc32",
                args='',
                channels=list(range(0, 1)),
            ),
        )
        self.usrp.set_antenna("RX2", 0)  # 设置天线端口
        self.usrp.set_gain(0, 0)  # 增益归零


        # 创建存储探针
        self.sink = blocks.vector_sink_c()
        self.connect(self.usrp, self.sink)

    def check_adc_noise(self):
        """采集样本并计算噪声功率"""
        self.start()  # 启动流图
        time.sleep(0.1)  # 等待采集
        self.stop()

        samples = np.array(self.sink.data())
        power = 10 * np.log10(np.mean(np.abs(samples) ** 2)) + 30  # 转换为dBm
        print(f"ADC噪声功率: {power:.1f} dBm (正常应<-90dBm)")
        return power


# 执行诊断
if __name__ == "__main__":
    tb = USRPDiagnostic()
    # 强制旁路LNA（部分设备支持）
    try:
        tb.usrp.set_gain(-10, "RF", 0)
    except:
        print("该设备不支持分频段增益控制")
    # 测试不同配置
    for freq in [100e6, 500e6, 900e6]:
        tb.usrp.set_center_freq(freq, 0)
        tb.usrp.set_gain(0, 0)
        power = tb.check_adc_noise()

        if power > -80:
            print(f"警告：在{freq / 1e6}MHz检测到异常高噪声！")